package com.beaven.imclient.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.beaven.imclient.R;
import com.beaven.imclient.base.BaseActivity;
import com.beaven.imclient.fragment.ChatGroupFragment;
import com.beaven.imclient.fragment.ChatUserFragment;
import com.beaven.imclient.utils.ActivityUtil;
import com.beaven.imclient.utils.ToastUtil;
import com.beaven.imclient.widget.DeviceBottomPopup;
import com.beaven.model.data.helper.DbHelper;
import com.beaven.model.data.helper.GroupHelper;
import com.beaven.model.data.helper.SessionHelper;
import com.beaven.model.data.helper.UserHelper;
import com.beaven.model.model.api.RspModel;
import com.beaven.model.model.db.Group;
import com.beaven.model.model.db.Message;
import com.beaven.model.model.db.Session;
import com.beaven.model.model.db.User;
import com.beaven.model.model.sp.Account;
import rx.Subscriber;
import rx.subscriptions.CompositeSubscription;

public class ChatActivity extends BaseActivity implements View.OnClickListener {

  // 接收者Id，可以是群，也可以是人的Id
  public static final String KEY_RECEIVER_ID = "KEY_RECEIVER_ID";
  // 是否是群
  private static final String KEY_RECEIVER_IS_GROUP = "KEY_RECEIVER_IS_GROUP";

  //好友聊天界面
  public static void showUser(Context context, String userId) {
    if (context == null || TextUtils.isEmpty(userId)) return;
    Intent intent = new Intent(context, ChatActivity.class);
    intent.putExtra(KEY_RECEIVER_ID, userId);
    intent.putExtra(KEY_RECEIVER_IS_GROUP, false);
    context.startActivity(intent);
  }

  //群聊界面
  public static void showGroup(Context context, String groupId) {
    if (context == null || TextUtils.isEmpty(groupId)) return;
    Intent intent = new Intent(context, ChatActivity.class);
    intent.putExtra(KEY_RECEIVER_ID, groupId);
    intent.putExtra(KEY_RECEIVER_IS_GROUP, true);
    context.startActivity(intent);
  }

  // 会话聊天界面
  public static void show(Context context, Session session) {
    if (session == null || context == null || TextUtils.isEmpty(session.getId())) return;
    Intent intent = new Intent(context, ChatActivity.class);
    intent.putExtra(KEY_RECEIVER_ID, session.getId());
    intent.putExtra(KEY_RECEIVER_IS_GROUP,
        session.getReceiverType() == Message.RECEIVER_TYPE_GROUP);
    context.startActivity(intent);
  }

  private String receiverId;
  private boolean isGroup;
  private Group group;
  private User user;
  private Session session;
  private Toolbar toolbar;
  private DeviceBottomPopup deviceBottomPopup;
  private View bottomView;
  private TextView text_content_center;
  private ProgressDialog dialog;
  private CompositeSubscription subscription = new CompositeSubscription();

  @Override public int getLayoutId() {
    return R.layout.activity_chat;
  }

  @Override protected void initBefore() {
    super.initBefore();
    receiverId = getIntent().getStringExtra(KEY_RECEIVER_ID);
    isGroup = getIntent().getBooleanExtra(KEY_RECEIVER_IS_GROUP, false);
    session = SessionHelper.findFromLocal(receiverId);
    if (isGroup) {
      group = GroupHelper.findFromLocal(receiverId);
    } else {
      user = UserHelper.findFromLocal(receiverId);
    }
  }

  @Override protected void initWidget() {
    super.initWidget();
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setBackgroundColor(getResources().getColor(R.color.primary));
    toolbar.setNavigationIcon(R.drawable.image_back_left);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        finish();
      }
    });
    View view_status_bar = findViewById(R.id.view_status_bar);
    view_status_bar.setBackgroundColor(getResources().getColor(R.color.primary));
    text_content_center = (TextView) findViewById(R.id.text_content_center);
    if (isGroup) {
      ImageView image_arrow_right_two = (ImageView) findViewById(R.id.image_arrow_right_two);
      image_arrow_right_two.setBackgroundResource(R.drawable.image_add);
      image_arrow_right_two.setOnClickListener(this);
      if (group.getOwner() != null && group.getOwner().getId().equals(Account.getUserId())) {
        ImageView image_arrow_right = (ImageView) findViewById(R.id.image_arrow_right);
        image_arrow_right.setBackgroundResource(R.drawable.image_setting);
        image_arrow_right.setOnClickListener(this);
      }
    }

    Fragment fragment = isGroup ? ChatGroupFragment.newInstance(receiverId)
        : ChatUserFragment.newInstance(receiverId);
    ActivityUtil.replaceFragmentToActivity(getSupportFragmentManager(), fragment,
        R.id.layout_chat_frame);
  }

  @Override protected void onResume() {
    super.onResume();
    if (isGroup) {
      group = GroupHelper.findFromLocal(receiverId);
    } else {
      user = UserHelper.findFromLocal(receiverId);
    }
    text_content_center.setText(isGroup ? group.getName() : user.getName());
    if (session != null) {
      session.setUnReadCount(0);
      session.update();
    }
  }

  @Override protected void onPause() {
    super.onPause();
    subscription.clear();
    hideLoading();
    if (session != null) {
      session.setUnReadCount(0);
      session.update();
    }
  }

  private void showBottomPup(int resourceId) {
    bottomView = LayoutInflater.from(this).inflate(resourceId, null);
    deviceBottomPopup = new DeviceBottomPopup(this, bottomView, toolbar,
        new ColorDrawable((getResources().getColor(android.R.color.transparent))),
        RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    bottomView.findViewById(R.id.text_dismiss).setOnClickListener(this);
  }

  @Override public void onClick(View v) {
    hideSoftInput(v.getWindowToken());
    switch (v.getId()) {
      case R.id.image_arrow_right_two:
        showBottomPup(R.layout.popu_group_add);
        bottomView.findViewById(R.id.text_member_add).setOnClickListener(this);
        break;
      case R.id.image_arrow_right:
        showBottomPup(R.layout.popu_group_setting);
        bottomView.findViewById(R.id.text_group_update).setOnClickListener(this);
        bottomView.findViewById(R.id.text_member_delete).setOnClickListener(this);
        bottomView.findViewById(R.id.text_group_delete).setOnClickListener(this);
        break;
      case R.id.text_dismiss:
        deviceBottomPopup.dismiss();
        break;
      case R.id.text_member_add:
        deviceBottomPopup.dismiss();
        GroupMemberActivity.start(ChatActivity.this, true, receiverId);
        break;
      case R.id.text_group_update:
        deviceBottomPopup.dismiss();
        SettingActivity.startGroupUpdate(ChatActivity.this, receiverId);
        break;
      case R.id.text_member_delete:
        deviceBottomPopup.dismiss();
        GroupMemberActivity.start(ChatActivity.this, false, receiverId);
        break;
      case R.id.text_group_delete:
        deviceBottomPopup.dismiss();
        deleteGroup();
        break;
      default:
        break;
    }
  }

  private void deleteGroup() {
    showLoading();
    subscription.add(GroupHelper.deleteGroup(receiverId).subscribe(new Subscriber<RspModel>() {
      @Override public void onCompleted() {

      }

      @Override public void onError(Throwable e) {
        hideLoading();
        ToastUtil.show(R.string.data_network_error);
      }

      @Override public void onNext(RspModel rspModel) {
        hideLoading();
        if (rspModel.isSuccess()) {
          DbHelper.instance().deleteModel(Group.class, group);
          if (session != null) {
            DbHelper.instance().deleteModel(Session.class, session);
          }
          finish();
        } else {
          ToastUtil.show(R.string.delete_error);
        }
      }
    }));
  }

  public void showLoading() {
    dialog = ProgressDialog.show(ChatActivity.this, "", getString(R.string.load_now));
  }

  public void hideLoading() {
    if (dialog != null) {
      dialog.dismiss();
    }
  }
}
